package com.za.plugin.transfer.func;


import com.za.plugin.pojo.Content;
import com.za.plugin.util.StrUtil;

// datediff() 转换
public class DatediffFunctionTransfer implements FunctionTransfer {
    @Override
    public boolean isSupport(String sql) {
        return clearSpace(sql).contains("datediff(");
    }

    private String clearSpace(String sql) {
        return sql.toLowerCase().replaceAll(" datediff\\s*\\(", " datediff(");
    }

    @Override
    public String transfer(String sql) {
        sql = clearSpace(sql);
        if (sql.contains("datediff(")) {
            int idx = sql.indexOf("datediff(");
            while (idx >= 0) {
                int left = sql.indexOf('(', idx);
                Content expectContent = StrUtil.getExpectContent(sql, left);
                String expectStr = expectContent.getExpectStr();
                int end = expectContent.getEnd();
                String sb = "datediff( day," + expectStr + " )";
                sql = sql.substring(0, idx) + sb + sql.substring(end);
                idx = sql.indexOf("datediff(", idx + "datediff(".length());
            }
        }
        return sql;
    }
}
